package com.general.framework.zzyy.thread01;

import java.util.concurrent.*;

/**
 * Future+线程池异步多线程任务配合，能显著提高程序的运行效率
 */

public class FutureThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 引入线程池解决每次都new Thread，无法复用的问题
         */
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        long startTime = System.currentTimeMillis();
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "task1 over";
        });

        // Thread t1 = new Thread(futureTask1, "T1");
        // t1.start();
        threadPool.submit(futureTask1);


        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "task2 over";
        });
        threadPool.submit(futureTask2);

        futureTask1.get();
        futureTask2.get();


        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("cost time: " + (endTime - startTime) + "ms");
        threadPool.shutdown();
    }
}
